<!--创建送货计划新版-->
<template>
	<div class="m-createDeliveryPlan m-window" v-loading="loading">
		<el-row :gutter="5" v-if="!showDemandPlan">
			<el-col :span="24">
				<el-row :gutter="10">
					<el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="saveDeliveryPlanData(1)"
							v-if="editModel!='view' && accountType==4 && headerForm.billState ==0"
						>发布</el-button>
					</el-col>

					<!-- <el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="saveDeliveryPlanData(1)"
							v-if="editModel!='view' && accountType==4 && headerForm.billState ==1&&headerForm.type==1"
						>确认发送</el-button>
					</el-col>-->
					<el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="confirmDeliveryPlanData(accountType)"
							v-if="editModel!='view' && accountType==4 && headerForm.billState ==1&&headerForm.type==0"
						>确认发送</el-button>
					</el-col>

					<el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="saveDeliveryPlanData(0)"
							v-if="editModel!='view' && accountType==4&& headerForm.billState <1"
						>保存</el-button>
					</el-col>

					<el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="saveDeliveryPlanDataPurchase(1)"
							v-if="editModel!='view' && accountType==1 && headerForm.billState<1"
						>发布</el-button>
					</el-col>
					<el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="saveDeliveryPlanDataPurchase(0)"
							v-if="editModel!='view' && accountType==1 && headerForm.billState<1"
						>保存</el-button>
					</el-col>

					<el-col :span="2" class="m-floatRight">
						<el-button
							type="primary"
							@click="confirmDeliveryPlanData(accountType)"
							v-if="editModel!='view' && accountType==1 && headerForm.billState==2"
						>确认</el-button>
					</el-col>

					<el-col :span="2" class="m-floatRight">
						<el-button type="primary" @click="selectBills" v-if="editModel=='create'&&accountType==4">选单</el-button>
					</el-col>
					<el-col
						:span="2"
						v-if="headerForm.billState==2&&accountType==1&&editModel!='view'"
						class="m-floatRight"
					>
						<el-button type="primary" @click="recallPlanBills(1)">退回</el-button>
					</el-col>

					<el-col
						:span="2"
						v-if="headerForm.billState==1&&accountType==1&&editModel!='view'"
						class="m-floatRight"
					>
						<el-button type="primary" @click="recallPlanBills(0)">收回</el-button>
					</el-col>

					<el-col
						:span="2"
						v-if="headerForm.billState==3&&accountType==4&&editModel!='view'&&headerForm.type==1"
						class="m-floatRight"
					>
						<el-button type="primary" @click="withdrawDeliveryPlan()">撤回</el-button>
					</el-col>
					<el-col :span="2" class="m-floatRight" v-if="editModel=='add'">
						<el-dropdown trigger="click" placement="bottom" @command="handleCommand">
							<el-button type="primary">
								选单
								<i class="el-icon-arrow-down el-icon--right"></i>
							</el-button>
							<el-dropdown-menu slot="dropdown" class="dropMenu">
								<el-dropdown-item command="1">导入</el-dropdown-item>
								<el-dropdown-item command="2">按需求</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</el-col>
					<el-col :span="2" class="m-floatRight">
						<el-button @click="goback(true)">返回</el-button>
					</el-col>
				</el-row>
			</el-col>
		</el-row>
		<el-row :gutter="5" v-if="!showDemandPlan">
			<el-form ref="headerForm" label-width="70px" :inline-message="true" label-position="left">
				<el-col :span="5" v-if="editModel!=='add'">
					<el-form-item label="计划单号" prop="planNo" class="rightItem">
						<el-input v-model="headerForm.planNo" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-form-item label="计划区间" class="rightItem">
						<el-date-picker
							v-model="headerForm.planSDate"
							type="date"
							placeholder="计划区间"
							value-format="yyyy-MM-dd"
							:disabled="editModel!='create' ||  dateSeleterReadOnly!=false"
						></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-date-picker
						v-model="headerForm.planEDate"
						type="date"
						placeholder="计划区间"
						value-format="yyyy-MM-dd"
						:disabled="editModel!='create' || dateSeleterReadOnly!=false"
						@change="changePlanEDate"
					></el-date-picker>
				</el-col>
				<el-col :span="5" v-if="editModel=='view'&&headerForm.billState==0">
					<el-form-item label="创建日期" class="rightItem">
						<el-input v-model="headerForm.createDate" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5" v-else>
					<el-form-item label="发布日期" prop="purOrdNo" class="rightItem">
						<el-input v-model="headerForm.releaseDate" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5" v-if="editModel=='view'&&headerForm.billState==0">
					<el-form-item label="创建人" class="rightItem">
						<el-input v-model="headerForm.creator" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="5" v-else>
					<el-form-item label="发布人" class="rightItem">
						<el-input v-model="headerForm.releaser" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-form>
		</el-row>
		<el-row v-if="headerForm.type==1&&!showDemandPlan">
			<el-form ref="headerForm" label-width="70px" :inline-message="true" label-position="left">
				<el-col :span="5">
					<el-form-item label="运输方" class="rightItem">
						<el-select v-model="headerForm.transport" clearable :disabled="editModel=='view'">
							<el-option
								v-for="option in transportList"
								:key="option.id"
								:value="option.transportName"
								:label="option.transportName"
							></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-form>
		</el-row>
		<div
			class="m-agTable m-top2"
			:class="{'m-top3':accountType==4&&headerForm.type==1}"
			v-if="!showDemandPlan"
		>
			<agGridComponents
				ref="agGirdComponent"
				:getGridOptions="gridOptions"
				:getColumnDefs="columnDefs"
				:defaultColDef="defaultColDef"
			></agGridComponents>
		</div>
		<!-- 选择需求计划创建送货计划单 -->
		<selectDemandPlan
			v-if="showDemandPlan"
			@goBack="showDemandPlan=false"
			@confirmCreate="confirmCreate"
		></selectDemandPlan>
		<!-- 展示备注详情弹窗 -->
		<el-dialog
			title="处理意见"
			:visible.sync="menoDialogVisible"
			width="50%"
			:before-close="closeDialog"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-card class="meno-card" v-for="(item,index) in menos" :key="index">
				<div slot="header" class="clearfix">
					<span>{{item.title}}</span>
					<p>{{item.title=='差异说明'?'确认时间':'关闭时间'}}：{{item.createDate}}</p>
				</div>
				<div>{{item.content}}</div>
			</el-card>
			<span slot="footer" class="dialog-footer"></span>
		</el-dialog>

		<el-dialog title="选择采购订单" :visible.sync="showPurchase" v-dialogDrag width="60%">
			<div style="600px">
				<select-purchase-bill :getSelectPurchase="getSelectPurchase"></select-purchase-bill>
			</div>
		</el-dialog>
		<!-- 送货单计划单导入弹窗-->
		<importDeliveryPlanDialog
			:importDialogVisible="importDialogVisible"
			v-if="importDialogVisible"
			@closeDialog="closeImportPlan"
			@saveImportData="saveImportData"
		></importDeliveryPlanDialog>
	</div>
</template>

<script>
import rendererFramework from './common/rendererFramework'
import selectPurchaseBill from "@/views/purchase/selectPurchaseBill";
import agGridComponents from "@/components/agGridComponents";
import importDeliveryPlanDialog from "./common/importDeliveryPlanDialog";
import selectDemandPlan from "./common/selectDemandPlan";
import { maxDate, minDate } from "@/util/format";
import Msg from "@/public/message"
import _Api from "@/api";
export default {
	name: 'createDeliveryPlan',
	components: {
		selectPurchaseBill,
		agGridComponents,
		importDeliveryPlanDialog,
		selectDemandPlan
	},
	data () {
		return {
			//主表表头信息
			headerForm: {
				planNo: '',
				planSDate: '',
				planEDate: '',
				releaser: '',
				releaseDate: '',
				releaserId: '',
				billState: 0   //0待发布，1待供方确认，2待购方确认，3全部确认，
			},
			columnDefs: [],
			gridOptions: {},
			rowData: [],
			//   底部栏合计数
			pinnedRowData: {
				totalPlan: 0,
				totalConfirm: 0
			},
			//   账户类型
			accountType: this.$global.user.userTypeId,
			// 差异说明内容
			diffContent: [],
			//  备注详情弹窗
			menoDialogVisible: false,
			// 备注详情内容
			menos: [],
			// 明细行差异说明内容
			diffValue: '',
			loading: false,
			showPurchase: false,
			//区间选择器默认为非只读   当选单后变成只读
			dateSeleterReadOnly: false,
			//记录区间天数
			dateColumnCount: 0,
			//计划区间开始的列数  用于遍历获取区间时间
			dateIndex: 0,
			defaultColDef: null,
			maxPlanMxNo: 0,     //记录明细的最大行号  用于编辑数据  在mounted时记录
			transportList: [],
			// 是否显示导入弹窗
			importDialogVisible: false,
			// 显示按需求创建送货计划页面
			showDemandPlan: false
		}
	},
	props: {
		removeTab: {
			type: Function
		},
		editModel: {
			type: String,
			default: 'add'
		},
		tabelData: {
			type: Array
		}
	},
	beforeMount () {
		//  表格配置项
		this.gridOptions = {
			context: {
				componentParent: this
			},
			//enableColResize: true,
			getContextMenuItems: [],
			defaultColDef: {
				menuTabs: []
			},
			pinnedBottomRowData: this.createBottomRow(1, "Bottom"),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
			},
			//   onRowSelected: this.rowSelected,
			suppressRowClickSelection: true,//单元格选中,false为选中整行
			headerHeight: 70,
			rowHeight: 70,
			components: {
				customPinnedRowRenderer: CustomPinnedRowRenderer,
				customPinnedRowRenderer2: CustomPinnedRowRenderer2,
				customPinnedRowRenderer3: CustomPinnedRowRenderer3,
				// customPinnedRowRenderer4:customPinnedRowRenderer4
			},
		}
		let setCellStyle = (pramas) => {
			const { state } = pramas.data
			// 已关闭的订单行背景变为灰色   
			if (state == 5) {
				return { backgroundColor: '#ededed' };
			} else {
				return { backgroundColor: null };
			}
		}
		// 表格列配置
		this.columnDefs = [
			{
				headerName: "物料编号",
				field: "matName",
				headerComponentFramework: rendererFramework.headerCell,
				cellRendererFramework: rendererFramework.columnCell,
				minWidth: 200,
				cellStyle: setCellStyle,
				pinned: "left"
			},
			{
				headerName: "采购方",
				field: "companyName",
				headerComponentFramework: rendererFramework.headerCell,
				cellRendererFramework: rendererFramework.columnCell,
				pinnedRowCellRenderer: 'customPinnedRowRenderer3',
				minWidth: 200,
				cellStyle: setCellStyle,
				width: 150,
				pinned: "left",
				resizable: true
			},
			{
				headerName: "订单号",
				field: "purOrdNo",
				headerComponentFramework: rendererFramework.headerCell,
				cellRendererFramework: rendererFramework.columnCell,
				pinnedRowCellRenderer: 'customPinnedRowRenderer',
				autoHeight: true,
				cellStyle: setCellStyle,
				width: 150,
				minWidth: 150,
				pinned: "left",
				resizable: true
			},
			{
				headerName: "计划量",
				field: "planAmount",
				headerComponentFramework: rendererFramework.headerCell,
				pinnedRowCellRenderer: 'customPinnedRowRenderer2',
				cellRendererFramework: rendererFramework.columnCell,
				cellStyle: setCellStyle,
				minWidth: 120,
				pinned: "left",
				resizable: true
			},
			{
				headerName: "操作",
				field: "opreator",
				cellRendererFramework: rendererFramework.operator,
				pinnedRowCellRenderer: 'customPinnedRowRenderer3',
				cellStyle: (pramas) => {
					const { state } = pramas.data
					// 已关闭的明细行背景置灰   
					if (state == 5) {
						return { backgroundColor: '#ededed', lineHeight: '70px', textAlign: 'center' };
					} else {
						return { backgroundColor: null, lineHeight: '70px', textAlign: 'center' };
					}
				},
				width: 120,
				minWidth: 100,
				pinned: "left",
				resizable: true
			}
		]
		this.defaultColDef = { suppressSizeToFit: true, }
	},
	mounted () {
		this.headerForm.releaser = this.$global.user.employeeName
		this.headerForm.releaserId = this.$global.user.id
		// this.headerForm.releaseDate = new Date().Format('yyyy-MMM-dd')
		if (this.accountType == 4) {          //供应商账号获取运输方
			this.getTranportList()
		}
		if (this.editModel == 'create') {
			this.headerForm.billState = 0
		}
		if (this.editModel == 'create' || this.editModel == 'add') {
			// create供方创建，add购方创建
			this.headerForm.type = this.accountType == 4 ? 1 : 0
		}
		if (this.tabelData.length > 0 && this.editModel != 'create') {
			this.rowData = []
			// 获取列表数据   
			this.tabelData.forEach(item => {
				this.rowData = [...this.rowData, ...item.deliveryplanmxs]
			})
			if (this.editModel == 'edit' || this.editModel == 'add') {
				this.dateColumnCount = this.tabelData[0].deliveryplanmxs.length > 0 ? this.tabelData[0].deliveryplanmxs[0].deliveryplantms.length : 0;
				this.dateIndex = this.columnDefs.length - 1;
				const { releaser, releaserId, releaseDate } = this.tabelData[0]
				this.headerForm = {
					...this.tabelData[0],
					releaser: releaser || this.$global.user.employeeName,
					releaserId: releaserId || this.$global.user.id,
					releaseDate: releaseDate || new Date().Format('yyyy-MMM-dd')
				}
				this.setrequirdColumn(this.rowData)
				this.maxPlanMxNo = Math.max(...this.rowData.map(row => { return row.planMxNo })) + 1
			} else if (this.editModel == 'view') {
				const { releaser, releaserId, releaseDate } = this.tabelData[0]
				this.headerForm = {
					...this.tabelData[0],
					releaser: releaser || this.$global.user.employeeName,
					releaserId: releaserId || this.$global.user.id,
					releaseDate: releaseDate || new Date().Format('yyyy-MMM-dd')
				}
				this.setrequirdColumn(this.rowData)
			}
		}
		// 购方创建计划单当供应商首次进行编辑的时候确认数量默认为计划数量
		if (this.$global.user.userTypeId == 4 && this.editModel != 'view' && this.headerForm.type === 0) {
			this.rowData.forEach(row => {
				let amount = 0
				if (row.state == 1) {
					row.deliveryplantms.forEach(el => {
						amount += Number(el.planAmount)
						el.confirmAmount = el.planAmount
					})
					row.confirmAmount = amount
					//  待确认状态时首次状态为无差异  
					row.state = 3
				}
			})
		}

		this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
		this.setPinnedData()
	},
	methods: {
        /**
		* @vuese
        * 下拉按钮点击下拉选项事件回调
        * @arg 参数为下拉选项key
		*/
		handleCommand (command) {
			switch (command) {
				case "1":
					this.importDialogVisible = true
					break;
				case "2":
					this.showDemandPlan = true
					break
			}
		},
        /**
		* @vuese
        * 导入组件关闭弹窗事件回调
		*/
		closeImportPlan () {
			this.importDialogVisible = false;
		},
        /**
		* @vuese
        * 导入组件确认导入数据事件回调
        * @arg 参数为导入的数据
		*/
		saveImportData (planRowData) {
			this.planRowData = planRowData;
			this.creationTab(this.tabData);
			this.importDialogVisible = false;
		},
		//  每日需求列配置
		setrequirdColumn (rowData, flag = true) {
			let requirdDates = []
			// 获取每日需求数据   
			rowData.forEach(row => {
				requirdDates = [...requirdDates, ...row.deliveryplantms]
			})
			// 每日需求数据去重并按日期进行排序
			let obj = {}
			requirdDates = requirdDates.reduce(function (item, next) {
				obj[next.requireDate] ? '' : obj[next.requireDate] = true && item.push(next);
				return item;
			}, []).sort((a, b) => {
				let time1 = new Date(a.requireDate).getTime()
				let time2 = new Date(b.requireDate).getTime()
				return time1 - time2
			})
			//  每日需求量列配置  
			requirdDates.forEach((item, index) => {
				//  
				if (this.accountType == 4 && this.headerForm.type == 1) {
					if (flag) {
						this.columnDefs.push({
							headerName: item.requireDate,
							field: "date" + index,
							width: 120,
							cellRendererFramework: rendererFramework.timeEditer,
							pinnedRowCellRenderer: 'customPinnedRowRenderer3',
							dateIndex: index,
							suppressSizeToFit: true,
						})
					}
				} else {
					this.columnDefs.push({
						headerName: item.requireDate,
						field: item.requireDate,
						cellRendererFramework: rendererFramework.editRequird,
						width: 150,
						cellStyle: (pramas) => {
							const { state } = pramas.data
							// 已关闭的明细行背景置灰   
							if (state == 5) {
								return { backgroundColor: '#ededed' };
							} else {
								return { backgroundColor: null };
							}
						},
						minWidth: 120
					})
				}
			})
			this.$nextTick(_ => {
				this.$refs['agGirdComponent'].gridOptions.api.setColumnDefs(this.columnDefs);
				this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
				this.$refs['agGirdComponent'].gridOptions.api.sizeColumnsToFit()
			})
		},
		// 确认创建
		confirmCreate (rowData) {
			let planRowData = []
			rowData.forEach(row => {
				for (let i = 0; i < planRowData.length; i++) {
					if (planRowData[i].purOrdNo == row.purOrdNo && planRowData[i].purOrdMxNo == row.purOrdMxNo
						&& planRowData[i].matCode == row.matCode && planRowData[i].area == row.area) {
						planRowData[i].deliveryplantms.push({
							creator: this.$global.userName,
							creatorId: this.$global.userId,
							planAmount: row.planAmount,
							requireDate: new Date(Date.parse(row.startSdate)).Format("yyyy-MM-dd"),
							requestMxId: row.id,
							requestId: row.requestId,
						})
						return
					}
				}
				planRowData.push({
					matCode: row.matCode,
					matName: row.matName,
					purOrdNo: row.purOrdNo,
					purOrdMxNo: row.purOrdMxNo,
					supplierCode: row.supplierCode,
					supplierName: row.supplierName,
					orderAmount: row.orderAmount,
					unitCode: row.unitCode,
					companyName: row.companyName,
					companyCode: row.companyCode,
					companyId: row.companyId,
					supplierId: row.supplierId,
					area: row.area,
					planAmount: 0,
					confirmAmount: 0,
					state: 0,
					deliveryplantms: [{
						creator: this.$global.userName,
						creatorId: this.$global.userId,
						planAmount: row.planAmount,
						requireDate: new Date(Date.parse(row.startSdate)).Format("yyyy-MM-dd"),
						requestMxId: row.id,
						requestId: row.requestId,
					}]
				})
			})
			let requirdDates = []
			planRowData.forEach(plan => {
				plan.deliveryplantms.forEach(el => {
					plan.planAmount += el.planAmount
					requirdDates.push(Date.parse(el.requireDate))
				})
			})
			let planEDate = maxDate(requirdDates)
			let planSDate = minDate(requirdDates)
			this.headerForm.planSDate = new Date(planSDate).Format("yyyy-MM-dd")
			this.headerForm.planEDate = new Date(planEDate).Format("yyyy-MM-dd")
			this.showDemandPlan = false
			this.rowData = planRowData
			this.setrequirdColumn(planRowData)
			this.setPinnedData()
		},
		//获取选择采购订单
		getSelectPurchase (rows) {
			this.showPurchase = false;
			rows.forEach(row => {
				let repeatFlag = false;
				this.rowData.forEach(item => {
					if (item.purOrdNo == row.purOrdNo) {
						repeatFlag = true;
					}
				})
				if (repeatFlag) return;
				row.deliveryplantms = []
				row.state = 0;
				row.supplierName = this.$global.supplierData.supplierName;
				row.supplierCode = this.$global.supplierData.supplierCode;
				row.planAmount = 0;
				row.confirmAmount = 0;
				row.planSDate = new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00")
				row.planEDate = new Date(this.headerForm.planEDate).Format("yyyy-M-d 00:00:00")
				for (let i = 0; i < this.dateColumnCount; i++) {
					let obj = {
						creator: this.$global.userName,
						creatorId: this.$global.userId,
						confirmAmount: 0,
						requireDate: this.columnDefs[this.dateIndex + i + 1].headerName,
					}
					row.deliveryplantms.push(obj)
				}
				this.rowData.push(row)
			})
			if (this.rowData.length > 0) {
				this.dateSeleterReadOnly = true;
			}
			this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
			this.$refs['agGirdComponent'].gridOptions.api.sizeColumnsToFit()
		},
		// 供应商保存送货计划   
		saveDeliveryPlanData (type) {
			const { releaser, releaserId, releaseDate } = this.headerForm
			if (this.headerForm.type == 1 && !this.headerForm.transport) {
				Msg.showPopMsg('运输方不能为空')
				return
			}
			this.loading = true
			if (this.editModel == 'create') {
				let sendData = {
					creator: this.$global.userName,
					creatorId: this.$global.userId,
					planSDate: new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00"),
					planEDate: new Date(this.headerForm.planEDate).Format("yyyy-M-d 00:00:00"),
					planNo: "",
					remark: "",
					type: 1,
					deliveryplanmxs: []
				}
				sendData.transport = this.headerForm.transport || null
				if (type == 1) {
					sendData.releaser = this.$global.userName
					sendData.releaserId = this.$global.userId
				}
				sendData.billState = type == 1 ? 3 : 0
				this.rowData.forEach((item, index) => {
					item.creator = sendData.creator
					item.creatorId = sendData.creatorId
					item.planMxNo = index + 1
					item.state = type == 0 ? 0 : 4
					sendData.deliveryplanmxs.push(item)
				})
				_Api.saveDeliveryPlan([sendData]).then(res => {
					this.loading = false
					if (res.data.code == 1) {
						Msg.showSuccessMsg('创建成功')
						this.goback()
					} else if (res.data.code == 0) {
						Msg.showErrorMsg(res.data.info)
					}
				}).catch(err => {
					this.loading = false
					Msg.showErrorMsg(err.data.info)
				})
			}
			else if (this.editModel == 'edit') {
				let sendData = {
					id: this.headerForm.id,
					modifyer: this.$global.userName,
					modifyerId: this.$global.userId,
					planSDate: new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00"),
					planEDate: new Date(this.headerForm.planEDate).Format("yyyy-M-d 00:00:00"),
					planNo: this.headerForm.planNo,
					type: this.headerForm.type,
					deliveryplanmxs: []
				}
				sendData.transport = this.headerForm.transport || ''
				if (type == 1) {
					sendData.releaser = this.$global.userName
					sendData.releaserId = this.$global.userId
				}

				if (this.headerForm.billState == 1) {       //供方编辑采购方
					sendData.billState = type == 1 ? 2 : 1
				} else if (this.headerForm.billState == 0) {     //供方编辑未发布
					sendData.billState = type == 1 ? 3 : 0
				}


				this.rowData.forEach((item, index) => {
					item.modifyer = this.$global.user.employeeName
					item.modifyerId = this.$global.user.id
					item.releaser = type > 0 ? releaser : ''
					item.releaserId = type > 0 ? releaserId : ''
					item.releaseDate = type > 0 ? releaseDate : ''

					item.planSDate = new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00")
					item.planEDate = new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00")
					item.modifyDate = new Date().Format("yyyy-M-d HH:mm:ss")
					item.sourcePlanNo = this.headerForm.planNo
					if (item.planMxNo == undefined) {
						item.planMxNo = this.maxPlanMxNo
						this.maxPlanMxNo++;
					}

					if (this.headerForm.type == 1) {        //计划方为供方
						item.state = type == 1 ? 4 : 0
					}
					// if(this.headerForm.type==1){        //计划方为供方
					//   item.state = type == 1 ? 4 : 0
					// }else{                              //计划方为采购方
					//   item.state = item.diffFlag == 1 ? 2 : 3
					// }
					sendData.deliveryplanmxs.push(item)
				})
				if (this.diffContent.length > 0) {
					Promise.all([this.saveDeliveryPlan(sendData), this.saveDiffContent(this.diffContent)]).then((result) => {
						this.loading = false
						Msg.showSuccessMsg('确认成功')
						this.goback()
					}).catch((error) => {
						this.loading = false
						Msg.showErrorMsg(error)
					})
				} else {
					this.saveDeliveryPlan(sendData).then(() => {
						this.loading = false
						Msg.showSuccessMsg('确认成功')
						this.goback()
					}).catch(err => {
						this.loading = false
						Msg.showErrorMsg(err)
					})
				}
			}
		},
		saveDeliveryPlan (sendData) {
			return new Promise((resolve, reject) => {
				_Api.saveDeliveryPlan([sendData]).then(res => {
					this.loading = false
					if (res.data.code == 1) {
						resolve()
					} else if (res.data.code == 0) {
						reject(res.data.info)
					}
				}).catch(err => {
					reject(err)
				})
			})
		},
		// 删除明细行
		deletedDeliveryPlanDetail (params) {
			const { rowIndex, data } = params
			if (Array.isArray(this.rowData) && this.rowData.length < 2 && this.editModel != "create") {
				Msg.showPopMsg("至少保留1条数据！")
				return
			}
			this.$confirm("是否确认删除该数据？", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				distinguishCancelAndClose: true
			}).then(_ => {
				if (data.id) {
					let obj = {
						id: data.id,
						modifyerId: this.$global.user.id,
						modifyer: this.$global.user.employeeName
					}
					this.$http.deleteDeliveryPlanItem(obj).then(({ data }) => {
						if (data.code == 1) {
							Msg.showSuccessMsg('删除成功')
							this.rowData.splice(rowIndex, 1)
							this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
							this.setPinnedData()
						} else {
							Msg.showErrorMsg(data.info)
						}
					}).catch(err => {
						Msg.showErrorMsg(err.data.message)
					})
				} else {
					this.rowData.splice(rowIndex, 1)
					this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
					this.setPinnedData()
				}
			})
		},
		// 填写差异说明
		diffrenceContent (nodeData) {
			if (this.diffContent.length > 0) {
				this.diffContent.forEach(item => {
					if (item.planMxID == nodeData.id) {
						this.diffValue = item.content
					}
				})
			}
			this.$prompt("差异备注", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				customClass: 'promitBox',
				inputType: 'textarea',
				inputValue: this.diffValue,
				distinguishCancelAndClose: true
			}).then(({ value }) => {
				if (this.diffContent.length > 0) {
					let planMxIds = []
					this.diffContent.forEach(item => {
						if (item.planMxID == nodeData.id) {
							item.content = value
						}
						planMxIds.push(item.planMxID)
					})
					if (planMxIds.indexOf(nodeData.id) == -1) {
						this.diffContent.push({
							content: value,
							creator: this.$global.user.employeeName,
							creatorId: this.$global.user.id,
							gReadFlag: 0,
							isSupSend: this.accountType == 4 ? 1 : 0,
							planMxID: nodeData.id,
							sender: this.$global.user.employeeName,
							senderId: this.$global.user.id,
							wReadFlag: 0
						})
					}
				} else {
					this.diffContent.push({
						content: value,
						creator: this.$global.user.employeeName,
						creatorId: this.$global.user.id,
						gReadFlag: 0,
						isSupSend: this.accountType == 4 ? 1 : 0,
						planMxID: nodeData.id,
						sender: this.$global.user.employeeName,
						senderId: this.$global.user.id,
						wReadFlag: 0
					})
				}
			}).catch(_ => { })
		},
		//选单
		selectBills () {
			if (this.headerForm.planSDate != "" && this.headerForm.planEDate != "") {
				this.showPurchase = true;
			} else {
				Msg.showPopMsg('请先选择计划区间')
				return
			}
		},
		// 供方或采购方确认保存送货计划明细
		confirmDeliveryPlanData (accountType) {
			this.loading = true
			let savePramas = {}
			if (accountType == 1) {
				// 采购确认主表状态变为全部确认,明细行状态变为生效  
				savePramas = {
					...this.tabelData[0],
					billState: 3,
					deliveryplanmxs: []
				}
				this.rowData.forEach((item, index) => {
					if (item.state != 5) {
						item.state = 4
						savePramas.deliveryplanmxs.push(item)
					}
				})
			} else if (accountType == 4) {
				//   判断是否所有明细行都无差异
				let noDifferent = this.tabelData[0].deliveryplanmxs.every(item => {
					return item.state == 3
				})
				if (noDifferent) {
					// 无差异所有明细行变为生效且自动确认无需购方确认
					this.tabelData[0].deliveryplanmxs.forEach(plan => {
						plan.state = 4
					})
					savePramas = {
						...this.tabelData[0],
						billState: 3
					}
				} else {
					//   供应商确认后状态变为待采购确认
					savePramas = {
						...this.tabelData[0],
						billState: 2
					}
				}
			}
			if (this.diffContent.length > 0) {
				Promise.all([this.savePlanDetailData(savePramas), this.saveDiffContent(this.diffContent)]).then((result) => {
					this.loading = false
					Msg.showSuccessMsg('确认成功')
					this.goback()
				}).catch((error) => {
					this.loading = false
					Msg.showErrorMsg(error)
				})
			} else {
				this.savePlanDetailData(savePramas).then(() => {
					this.loading = false
					Msg.showSuccessMsg('确认成功')
					this.goback()
				}).catch(err => {
					this.loading = false
					Msg.showErrorMsg(err)
				})
			}
		},
		// 保存差异说明
		saveDiffContent (params) {
			return new Promise((resolve, reject) => {
				this.$http.savePlanDiffContent(params).then(({ data }) => {
					if (data.code == 1) {
						resolve()
					} else {
						reject(data.info)
					}
				}).catch(err => {
					reject(err.data.message)
				})
			})
		},
		// 保存送货计划明细数据
		savePlanDetailData (params) {
			return new Promise((resolve, reject) => {
				this.$http.saveDeliveryPlanDetail(params).then(({ data }) => {
					if (data.code == 1) {
						resolve()
					} else {
						reject(data.info)
					}
				}).catch(err => {
					reject(err.data.message)
				})
			})
		},
		// 退回或者收回送货计划明细
		recallPlanBills (state) {
			let pramas = this.tabelData[0]
			let msg = ''
			pramas.billState = state
			// state为0收回,为1退回   
			if (state == 0) {
				pramas.deliveryplanmxs.forEach(item => {
					item.state = 0
				})
				pramas.modifyer = this.$global.user.employeeName
				pramas.modifyerId = this.$global.user.id
				msg = "收回"
			} else {
				pramas.retFlag = 1
				msg = '退回'
			}
			this.loading = true
			this.savePlanDetailData(pramas).then(_ => {
				this.loading = false
				Msg.showSuccessMsg(`${msg}成功`)
				this.goback()
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err)
			})
		},
		// 供方创建送货计划单撤回
		withdrawDeliveryPlan () {
			const { id } = this.headerForm
			this.loading = true
			this.$http.withdrawDeliveryPlan({ planId: id }).then(({ data }) => {
				this.loading = false
				if (data.code == 1) {
					Msg.showSuccessMsg('撤回成功')
					this.goback()
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 查看处理意见详情
		checkPlanMeno (nodeData) {
			this.$http.getPlanDiffContent({ planMxId: nodeData.id }).then(({ data }) => {
				if (data.code == 1) {
					if (data.rows.remark) {
						this.menos.push({
							content: data.rows.remark,
							title: '关闭说明',
							createDate: data.rows.modifyDate
						})
					}
					if (data.rows.deliveryplanmenos.length > 0) {
						this.menoDialogVisible = true
						data.rows.deliveryplanmenos.forEach(item => {
							item.title = '差异说明'
						})
						this.menos = [...this.menos, ...data.rows.deliveryplanmenos]
					}
					if (this.menos.length == 0) {
						Msg.showPopMsg('暂无相关处理意见！')
					}
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 关闭异常说明弹窗
		closeDialog () {
			this.menoDialogVisible = false
			this.menos = []
		},
		// 关闭明细行
		closePlanDetail (nodeData) {
			this.$prompt("关闭说明", "消息提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				customClass: 'promitBox',
				inputType: 'textarea',
				distinguishCancelAndClose: true
			}).then(({ value }) => {
				let params = {
					...nodeData,
					deliveryplantms: null,
					state: 5,
					remark: value
				}
				this.$http.closeDeliveryPlanDetail(params).then(({ data }) => {
					if (data.code == 1) {
						this.loadDeliveryPlanDetail(this.headerForm.id)
					} else {
						Msg.showErrorMsg(data.info)
					}
				}).catch(err => {
					Msg.showErrorMsg(err.data.message)
				})
			}).catch(_ => { })
		},
		// 调接口获取计划单详情数据
		loadDeliveryPlanDetail (planId) {
			this.loading = true
			this.$http.getDeliveryPlanDetail({ id: planId }).then(({ data }) => {
				this.loading = false
				if (data.code == 1) {
					this.rowData = data.rows.deliveryplanmxs
					this.headerForm.deliveryplanmxs = this.rowData
					this.setrequirdColumn(this.rowData, false)
					this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		// 关闭tab页
		goback () {
			if (this.editModel == 'add') {
				this.removeTab()
			} else {
				this.$emit('cancelComponents', true)
			}
		},
		// 创建底部栏
		createBottomRow (count, prefix) {
			var result = [{
				purOrdNo: '',
				planAmount: this.pinnedRowData
			}
			]
			return result
		},
		// 设置底部固定栏的数据
		setPinnedData () {
			this.pinnedRowData = {
				totalPlan: 0,
				totalConfirm: 0
			}
			this.rowData.forEach(row => {
				this.pinnedRowData.totalPlan += row.planAmount
				this.pinnedRowData.totalConfirm += row.confirmAmount ? row.confirmAmount : 0
			})
			this.$nextTick(_ => {
				this.$refs['agGirdComponent'].gridOptions.api.setPinnedBottomRowData(this.createBottomRow(1, "Bottom"))
			})
		},
		// 供方创建计划选择日期变化回调
		changePlanEDate () {
			let startDate = Date.parse(this.headerForm.planSDate);
			let endDate = Date.parse(this.headerForm.planEDate);
			let dateSpan = Math.floor((endDate - startDate) / (24 * 3600 * 1000));    //开始与结束的天数差
			this.dateColumnCount = dateSpan + 1;                                  //获取需求日期列的渲染列数
			this.columnDefs.length = 5
			this.dateIndex = this.columnDefs.length - 1;                          //获取需求日期列在哪一列开始渲染
			if (dateSpan < 0) {
				Msg.showErrorMsg("开始日期不能大于结束日期");
				this.headerForm.planEDate = "";
				return;
			} else if (dateSpan > 7) {
				Msg.showErrorMsg("最多只能做7天内的计划");
				this.headerForm.planEDate = "";
				return;
			}
			for (let i = 0; i <= dateSpan; i++) {
				let date = new Date(this.headerForm.planSDate);
				let nextDay = new Date(date.setDate(date.getDate() + i)).Format('yyyy-MMM-dd')
				this.columnDefs.push({
					headerName: nextDay,
					field: "date" + i,
					width: 120,
					suppressSizeToFit: true,
					cellRendererFramework: rendererFramework.timeEditer,
					pinnedRowCellRenderer: 'customPinnedRowRenderer3',
					dateIndex: i
				})
			}
			this.$refs['agGirdComponent'].gridOptions.api.setColumnDefs(this.columnDefs);
			this.$refs['agGirdComponent'].gridOptions.api.sizeColumnsToFit()
		},
		// 创建固定栏
		setPlanAmountCell () {
			this.$refs['agGirdComponent'].gridOptions.api.setRowData(this.rowData)
			this.setPinnedData()
		},
		// 购方创建计划单保存或发布。type为0保存，1发布
		saveDeliveryPlanDataPurchase (type) {
			this.loading = true
			if (this.editModel == 'create' || this.editModel == 'add') {
				let sendData = {
					creator: this.$global.userName,
					creatorId: this.$global.userId,
					planSDate: new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00"),
					planEDate: new Date(this.headerForm.planEDate).Format("yyyy-M-d 00:00:00"),
					planNo: "",
					remark: "",
					type: 0,
					deliveryplanmxs: []
				}
				if (type == 1) {
					sendData.releaser = this.$global.userName
					sendData.releaserId = this.$global.userId
					sendData.billState = this.accountType == 4 ? 3 : 1
				} else if (type == 0) {
					sendData.billState = 0
				}
				this.rowData.forEach((item, index) => {
					item.planMxNo = index + 1
					type == 0 ? item.state = 0 : item.state = 1
					sendData.deliveryplanmxs.push(item)
				})
				_Api.saveDeliveryPlan([sendData]).then(res => {
					this.loading = false
					if (res.data.code == 1) {
						Msg.showSuccessMsg('创建成功')
						this.goback()
					} else if (res.data.code == 0) {
						Msg.showErrorMsg(res.data.info)
					}
				}).catch(err => {
					this.loading = false
					Msg.showErrorMsg(err.data.info)
				})
			}
			else if (this.editModel == 'edit') {
				let sendData = {
					id: this.headerForm.id,
					planNo: this.headerForm.planNo,
					type: this.headerForm.type,
					modifyer: this.$global.userName,
					modifyerId: this.$global.userId,
					planSDate: new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00"),
					planEDate: new Date(this.headerForm.planEDate).Format("yyyy-M-d 00:00:00"),
					deliveryplanmxs: []
				}
				if (type == 1) {
					sendData.releaser = sendData.modifyer
					sendData.releaserId = sendData.modifyerId
				}
				sendData.billState = type == 1 ? 1 : 0
				this.rowData.forEach((item, index) => {
					item.modifyer = sendData.modifyer
					item.modifyerId = sendData.modifyerId
					item.releaser = type > 0 ? sendData.modifyer : ''
					item.releaserId = type > 0 ? sendData.modifyerId : ''
					item.releaseDate = type > 0 ? new Date().Format("yyyy-M-d 00:00:00") : ''
					item.planSDate = new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00")
					item.planEDate = new Date(this.headerForm.planSDate).Format("yyyy-M-d 00:00:00")
					item.modifyDate = new Date().Format("yyyy-M-d HH:mm:ss")
					item.sourcePlanNo = this.headerForm.planNo
					if (item.planMxNo == undefined) {
						item.planMxNo = this.maxPlanMxNo
						this.maxPlanMxNo++;
					}

					if (this.headerForm.billState == 0) {
						item.state = type == 1 ? 1 : 0
					} else if (this.headerForm.billState == 2) {
						item.state = type == 1 ? 1 : 2
					}
					sendData.deliveryplanmxs.push(item)
				})
				this.saveDeliveryPlan(sendData).then(() => {
					this.loading = false
					Msg.showSuccessMsg('确认成功')
					this.goback()
				}).catch(err => {
					this.loading = false
					Msg.showErrorMsg(err)
				})
			}
		},
		purChaseAffirm () {
			this.headerForm.deliveryplanmxs.forEach(item => {
				item.state = item.state == 5 ? 5 : 4
			})
			this.headerForm.billState = 3
			this.saveDeliveryPlan(this.headerForm).then(() => {
				this.loading = false
				Msg.showSuccessMsg('确认成功')
				this.goback()
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err)
			})
		},
		// 获取已启用并已创建账号运输方
		getTranportList () {
			_Api.selectTransportList({ supplierCode: this.$global.supplierData.supplierCode, flag: 1 }).then(res => {
				if (res.data.code == 1) {
					this.transportList = res.data.rows;
				}
			})
		}
	}
}
function CustomPinnedRowRenderer () { }

CustomPinnedRowRenderer.prototype.init = function (params) {
	delete params.data.confirmAmount;
	this.eGui = document.createElement('div');
	this.eGui.style.lineHeight = '70px'
	this.eGui.style.textAlign = 'center'
	this.eGui.innerHTML = '合计'
};

CustomPinnedRowRenderer.prototype.getGui = function () {
	return this.eGui
}
function CustomPinnedRowRenderer2 () { }

CustomPinnedRowRenderer2.prototype.init = function (params) {
	delete params.data.confirmAmount;
	this.eGui = document.createElement('div');
	this.eGui.setAttribute('id', 'totalCell');
	this.eGui.style.textAlign = 'center'
	let child1 = document.createElement('p')
	child1.style.color = '#333'
	child1.innerHTML = params.value.totalPlan
	this.eGui.appendChild(child1)
	let child2 = document.createElement('p')
	child2.innerHTML = params.value.totalConfirm
	this.eGui.appendChild(child2)
};

CustomPinnedRowRenderer2.prototype.getGui = function () {
	return this.eGui
}
function CustomPinnedRowRenderer3 () { }

CustomPinnedRowRenderer3.prototype.init = function (params) {
	delete params.data.confirmAmount;
	this.eGui = document.createElement('div');
	this.eGui.innerHTML = ''
};

CustomPinnedRowRenderer3.prototype.getGui = function () {
	return this.eGui
}


</script>

<style lang="less">
.m-createDeliveryPlan {
	.ag-header-cell-resize {
		width: 5px !important;
	}
	span.ag-header-cell-text {
		width: 100%;
		text-align: center;
	}
	.ag-theme-balham .ag-header-cell::after,
	.ag-theme-balham .ag-header-group-cell::after {
		content: none !important;
	}
	.m-agTable {
		bottom: 5px;
		.ag-header-cell {
			line-height: 70px;
			.ag-header-cell-resize {
				width: 2.5px;
				border-left: 1px solid #e4e7ed;
			}
		}
		.ag-cell {
			// line-height: 70px;
		}
	}
	.el-dialog__body {
		min-height: 400px;
	}
	.meno-card {
		margin-bottom: 10px;
		.el-card__header {
			padding: 10px 20px;
			.clearfix {
				display: flex;
				justify-content: space-between;
				p {
					flex: 1;
					text-align: right;
				}
			}
		}
	}
	.numberCell {
		height: 100%;
		text-align: center;
		.numberInput {
			width: 100%;
			input {
				width: 100%;
				border-radius: 2px;
				height: 25px;
			}
		}
	}
	.m-floatRight {
		/deep/ .el-dropdown {
			width: 100%;
		}
	}
}
.m-girdHeader {
	text-align: center;
	line-height: 22px;
	.cellContent {
		div {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}
}
.m-editRequird {
	.el-input {
		.el-input__inner {
			height: 26px;
			line-height: 26px;
		}
	}
}
</style>




